<?php
/**
 * Created by PhpStorm.
 * User: xianxuefeng
 * Date: 2018/5/14
 * Time: 17:36
 */

namespace app\controllers\marketing;

use Yii;
use GuzzleHttp\Client;
//use app\models\marketing\GoodsDataPremium;
use app\models\Elog;
use yii\data\Pagination;
use app\models\AutoMailTemplate;
use yii\web\Controller;
use app\components\TemplateMarket;

class AutoTemplateController extends \app\base\Controller
{

    private $getPriceApiUrl; // 获取商品详情页面价格url地址
    private $tokenId; // 秘钥相关
    private $header; // 设置专享价密文头部信息
    public $enableCsrfValidation=false;
    public function init()
    {

        $this->getPriceApiUrl = [
            'dev'=>'http://10.40.2.109:2087/gateway',
            'test'=>'http://10.40.2.109:2087/gateway',
            'product'=>'http://gb-obs-outer.gw-soa.com/gateway/'
        ];

        $this->tokenId = [
            'dev'=>'9c17830f2e3c20e61948653d0697be8f',
            'test'=>'9c17830f2e3c20e61948653d0697be8f',
            'product'=>'5dd73f1f0412b1a8f483ed0655b259b4',
        ];


        // 设置专享价密文头部信息, 这些接口对接的都是obs系统（如何判读接口是obs还是soa呢？service=com.globalegrow.spi.m中spi.后面有m的是obs或则为soa)
        $this->header = [
            "gearbest" =>
                [   // 查询商品部分信息 http://wiki.hqygou.com:8090/pages/viewpage.action?pageId=46498727
                    'queryGoodsSimpleInfo' => \GuzzleHttp\json_encode(
                        [
                            'service' => 'com.globalegrow.spi.mgoods.common.inter.IGoodsListAggregateService',
                            'method'  => 'queryGoodsSimpleInfo',
                            'domain'  => '',
                            'version' => '1.0.0',
                            'tokenId' => $this->tokenId[YII_ENV]
                        ]
                    ),
                    // 查询站点虚拟仓列表接口 http://wiki.hqygou.com:8090/pages/viewpage.action?pageId=27102833
                    'getVirtualWareshouseList' => \GuzzleHttp\json_encode(
                        [
                            'service' => 'com.globalegrow.spi.mstock.inter.IVirtualWarehouseService',
                            'method'  => 'getVirtualWareshouseList',
                            'domain'  => '',
                            'version' => '1.0.0',
                            'tokenId' => $this->tokenId[YII_ENV]
                        ]
                    ),
                    //  币种查询 document url : http://wiki.hqygou.com:8090/pages/viewpage.action?pageId=15371583
                    'querySiteCurrencyRateList' => \GuzzleHttp\json_encode(
                        [
                            'service' => 'com.globalegrow.spi.mpay.inter.PaySiteCurrencyRateService',
                            'method'  => 'querySiteCurrencyRateList',
                            'domain'  => '',
                            'version' => '1.0.0',
                            'tokenId' => $this->tokenId[YII_ENV]
                        ]
                    ),

                    // 查询商品的价格 document url : http://wiki.hqygou.com:8090/pages/viewpage.action?pageId=15371214
                    'getPriceList' => \GuzzleHttp\json_encode(
                        [
                            'service' => 'com.globalegrow.spi.mpromotion.common.inter.PriceApi',
                            'method'  => 'multiGet',
                            'domain'  => '',
                            'version' => '1.0.0',
                            'tokenId' => $this->tokenId[YII_ENV]
                        ]
                    ),
                    // 查询商品的价格 document url : http://wiki.hqygou.com:8090/pages/viewpage.action?pageId=15371214
                    'batchQueryGoodsPriceInfoList' => \GuzzleHttp\json_encode(
                        [
                            'service' => 'com.globalegrow.mgoods.spi.inter.IGoodsPriceRelationService',
                            'method'  => 'batchQueryGoodsPriceInfoList',
                            'domain'  => '',
                            'version' => '1.0.0',
                            'tokenId' => $this->tokenId[YII_ENV]
                        ]
                    ),


                ]
        ];
        // 获取币种汇率头部信息

    }

    private function error($msg = '系统繁忙') {
        if (empty($msg)) {
            $msg = '系统繁忙';
        }
        exit(json_encode(['status' => 0,'msg' => $msg,'data' => []]));
    }
    private function success($data = [],$msg = '成功') {
        exit(json_encode(['status' => 1,'msg' => $msg,'data' =>$data]));
    }
    /**
     * 模版类型添加
     * site_id 网站
     * template_name 模板名称，统一网站下，邮件模板名称唯一（与模板管理的模板名称数据共用）
     * template_content
     * type_id 模板id 
     * response
     *      {
     *       "status":1,
     *       "msg":"成功",
     *       "data":{
     *       "id":"576"
     *       }
     *      }
     */
    public function actionAddTemplate()
    {
        $params = $_REQUEST;
        if (! isset($params['site_id']) ||  empty($params['site_id'])  ||  ! is_numeric($params['site_id'])) {
            self::error('网站类型不能为空');
        }
        if (! isset($params['template_name']) ||  empty($params['template_name'])) {
            self::error('名称不能为空');
        }
        if ( isset($params['template_content']) &&  empty($params['template_content'])) {
            self::error('内容不能为空');
        }
        $ciphertext = '';
        if (  isset($params['ciphertext']) && ! empty($params['ciphertext'])) {
            $ciphertext = $params['ciphertext'];
        }
        $shop_info ='';

        if ( isset($params['shop_info']) && ! empty($params['shop_info']) ) {
            $shop_info = $params['shop_info'];
        }

        if ( ! isset($params['type_id']) || empty($params['type_id']) ) {
            $params['type_id'] = 0;
        }
        $session        = Yii::$app->session;
        $admin_info     = $session['admin_info'];
        $addSaid = $admin_info['real_name'];

        //确保模板名字的唯一性
//        $params['site_id'] = 12;
//        $params['template_subject'] = "123a";
        // author xianxuefeng
        $sql = "select id from auto_mail_template where template_name = '{$params['template_name']}' and is_del=0 ";
        $resSourceInfo = yii::$app->db->createCommand($sql)->queryOne();
        if (! empty($resSourceInfo)) {
            $msg = $params['template_name']. "此模板名称已存在";
            self::error($msg);
        }
        // 添加模版类型
        $sql = "select id from mail_template where template_name = '{$params['template_name']}' and is_del=0 ";
        $mailTemplateInfo = yii::$app->db->createCommand($sql)->queryOne();
        if (! empty($mailTemplateInfo)) {
            $msg = $params['template_name']. "此名称，在模板列表中已经重名";
            self::error($msg);
        }
        $insertRes = yii::$app->db->createCommand()->insert('auto_mail_template',[
            'template_name' => $params['template_name'],
            'template_content' => $params['template_content'],
            'site_id' => $params['site_id'],
            'add_said' => $addSaid,
            'shop_info' => $shop_info,
            'ciphertext' => $ciphertext,
            'type_id'    => $params['type_id'],  //模板id
            'last_modify' => time(),
        ])->execute();
        if (empty($insertRes)) {
            self::error($msg);
        }
        $id = yii::$app->db->getLastInsertID();
        self::success(['id' => $id]);
    }
    
    /*
     * 获取指定id的自定义模板数据
     */
    public function actionGetAutoTemplateById()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $id = Yii::$app->request->$mothod('id');
        $id = $id ? intval($id) : 0;
        if(!$id) {
            $this->returnJson(10008, "参数不存在！");
        }
        $autoMailModel = new AutoMailTemplate;
        $templateInfo = $autoMailModel->getAutoMailTemplateById($id);
        if(!$templateInfo) {
            $this->returnJson(10008, "模板数据不存在！");
        } else {
            $this->returnJson(0, "success", $templateInfo);
        }
        
    }
    
    /*
     * 获取指定站点的而所有自定义模板
     */
    public function actionGetAutoMailTemplateBySiteId()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $siteId = Yii::$app->request->$mothod('site_id');
        if(!$siteId) {
            $this->returnJson(10008, "参数不存在！");
        }
        
        $autoMailModel = new AutoMailTemplate;
        // 获取当前站点下所有的自定义模板
        $allAutoTemplates = $autoMailModel->getAutoMailTemplateBySiteId($siteId);
        $autoTem = [];
        $allAutoTemplatesStr = '<select id="custom_choose"  name="template_name" class="form-control z-select mr10 mb5" style="width:400px;"><option value="0" selected>--请选择自定义模板--</option>';
        foreach($allAutoTemplates as $allAutoTemplate) {
            $allAutoTemplatesStr .= '<option value="'.$allAutoTemplate['id'].'" temid="'.$allAutoTemplate['id'].'">'.$allAutoTemplate['template_name'].'</option>';
        }
        $allAutoTemplatesStr .= '</select>';
        $this->returnJson(0, "success", $allAutoTemplatesStr);
        
    }
    /*
     * 自定义模板添加至模板表
     * @liugang 2018-6-26
     */
    public function actionAddToTemplate()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $id = Yii::$app->request->$mothod('id');
        $type = Yii::$app->request->$mothod('type');
        $formData = Yii::$app->request->$mothod();
        
        $autoMailModel = new AutoMailTemplate;
        
        if(isset($type) && $type == 'add_temtype'){
            $templateInfo = [
                'site_id' => $formData['site_id'],
                'ciphertext' => '',
                'id'  => 0,
                'template_content' => ''
            ];
        } else {
            $id = $id ? intval($id) : 0;
            if(!$id) {
                $this->sysMsg('警告', '参数不存在!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            }
            
            $templateInfo = $autoMailModel->getAutoMailTemplateById($id);
            if(!$templateInfo) {
                $this->sysMsg('警告', '模板数据不存在!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            }
            $formData['site_id'] = $templateInfo['site_id'];
        }
        
        // 获取当前站点下所有的自定义模板
        $allAutoTemplates = $autoMailModel->getAutoMailTemplateBySiteId($formData['site_id']);
        $autoTemplate = [];
        foreach($allAutoTemplates as $allAutoTemplate) {
            $autoTemplate[$allAutoTemplate['id']] = $allAutoTemplate['template_name'];
        }
        
        
       
        // 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getMarketEmailAccessSite();
        
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
                $siteCode[$siteInfo_tmp_v['site_id']] = Yii::$app->params['sites']['marketing_email']['web_config'][$siteInfo_tmp_v['name']]['brief_code'];
            }
        }
       
        if (empty($siteInfo)) {
            exit('你好，你没有任何网站的相关权限');
        }
        $formData['siteInfo'] = $siteInfo;
        $formData['siteCode'] = $siteCode;
        // 当前搜索哪个网站的用户信息
       
        // 获取模版类型
        $TemplateMarket = new TemplateMarket();
        $templateTypeArr = $TemplateMarket->getTemplateType($formData['site_id']);
        $templateTypeArrInfo = [];
        $templateTypeArrInfo[0] = '--选择类型--';
        $templateTypeArrCompaign = [];
        $templateTypeArrCompaign[0] = '--选择类型--';
        $templateTypeArrTrigger = [];
        $templateTypeArrTrigger[0] = 1;
        $templateTypeArrTriggerReal = [];
        $templateTypeArrTriggerReal[0] = 1;
        
        $formData['tempType'] = [];
        $formData['temp_type_id'] = !empty($formData['temp_type_id']) ? $formData['temp_type_id'] : 0;
        $formData['tempTypeCompaign'] = [];
        $formData['tempTypeTrigger'] = [];
        $formData['tempTypeTriggerReal'] = [];
        $activeTemplateNum = [];
        $activeTemplateNumDeal = [];
        $selfMotionArr = [];
        $selfMotionStr = "";
        if (isset($templateTypeArr) && is_array($templateTypeArr)) {
            $templateTypeIdArr = [];
            $templateTypeIdStr = '';
            
            foreach ($templateTypeArr as $templateTypeArrK => $templateTypeArrV) {
                if ($templateTypeArrV['trigger_type'] == 0) { // 说明是自动触发的相关邮件
                    $templateTypeIdArr[] = $templateTypeArrV['id'];
                } 
            }
          
            $templateTypeIdStr = join(',',$templateTypeIdArr);
            if ($templateTypeIdStr) { // 获取每个模版类型下是否有启用的模版
                $activeTemplateNum = $TemplateMarket->getUsedTemplateNumByTypeId($templateTypeIdStr);
                foreach ($activeTemplateNum as $activeTemplateNumK => $activeTemplateNumV) {
                    $activeTemplateNumDeal[$activeTemplateNumV['type_id']] = $activeTemplateNumV;
                }
            }
           
            foreach ($templateTypeArr as $templateTypeArrK => $templateTypeArrV) {
                $templateTypeArrInfo[$templateTypeArrV['id']] = $templateTypeArrV['template_type_name'];
                $templateTypeArrCompaign[$templateTypeArrV['id']] = $templateTypeArrV['template_type_compaign'];
                if ($templateTypeArrV['trigger_type'] == 0 && isset($activeTemplateNumDeal[$templateTypeArrV['id']]) && $activeTemplateNumDeal[$templateTypeArrV['id']] > 0 ) { // 如果是自动发送的邮件模版类型，并且当前模版类型有启用的模版
                    $templateTypeArrTrigger[$templateTypeArrV['id']] = 0;
                } else {
                    $templateTypeArrTrigger[$templateTypeArrV['id']] = 1; 
                }
                
                if ($templateTypeArrV['trigger_type'] == 0) {
                    $selfMotionArr[] = $templateTypeArrV['id'];
                    $templateTypeArrTriggerReal[$templateTypeArrV['id']] = 0;
                } else {
                    $templateTypeArrTriggerReal[$templateTypeArrV['id']] = 1;
                }
            } 
            $formData['temp_type_id'] = !empty($formData['temp_type_id']) ? $formData['temp_type_id'] : 0;
            $formData['tempType'] = $templateTypeArrInfo;
            $formData['tempTypeCompaign'] = $templateTypeArrCompaign;
            $formData['tempTypeTrigger'] = $templateTypeArrTrigger;
            $formData['tempTypeTriggerReal'] = $templateTypeArrTriggerReal;
            $selfMotionStr = join(',' , $selfMotionArr);
           
        }
        
        return $this->render('//marketing//mail-template/add',[
            'data' => $templateInfo,
            'site'    => $site,
            'autoTemplate'    => $autoTemplate,
            'formData' => $formData,
            'selfMotionStr' => $selfMotionStr,
            'type' => 'auto_template'
        ]);
    }
    
    /**
     *  模板更新
     *  id   auto_mail_template
     *  site_id
     *  template_name
     *  template_subject 模板标题
     *  template_content
     *  status
     *
     */
    public function actionSaveTemplate() {
        $params = $_REQUEST;
        $data = [];
        if (! isset($params['id']) || empty($params['id']) ) {
            self::error("模板id 不能为空");
        }
        if ( isset($params['site_id'])&&  ! empty($params['site_id']) ) {
           $data['site_id'] = $params['site_id'];
        }
        if ( isset($params['template_name']) &&  ! empty($params['template_name'])) {
            $data['template_name'] = $params['template_name'];
        }
        if ( isset($params['template_content']) &&  ! empty($params['template_content'])) {
            $data['template_content'] = $params['template_content'];
        }

        if (isset($params['ciphertext']) &&  ! empty($params['ciphertext'])) {
            $data['ciphertext'] = $params['ciphertext'];
        }
        if ( isset($params['shop_info']) && ! empty($params['shop_info']) ) {
            $data['shop_info'] = $params['shop_info'];
        }

        if (  isset($params['type_id']) && ! empty($params['type_id']) ) {
            $data['type_id'] = $params['type_id'];
        }


        if (empty($data)) {
            self::success([],'没有要更改的信息');
        }
        $session        = Yii::$app->session;
        $admin_info     = $session['admin_info'];
        $addSaid = $admin_info['real_name'];
        $data['add_said'] = $addSaid;
        $data['last_modify'] = time();

        $cond = ['id' => $params['id']];
        $res = Yii::$app->db->createCommand()->update('auto_mail_template',$data, $cond)->execute();
        if (empty($res)) {
            self::error();
        }
        self::success();
    }


    /**
     *  模板列表
     *  id   auto_mail_template
     *  site_id         网站id
     *  template_name   模板名称
     *  page  也是
     *  count
     *
     *
     */
    public function actionTemplateList() {
        $params = $_REQUEST;
        $data = [];

        $where = " is_del = 0 ";      //只展示没有删除的模板
        if ( isset($params['site_id'])&&  ! empty($params['site_id']) ) {
            $data['site_id'] = $params['site_id'];
            if($params['site_id'] != 12){
                $where .= " and site_id in (19,{$params['site_id']})  ";
            }else{
                $where .= " and site_id = {$params['site_id']}  ";
            }
        }
        if ( isset($params['template_name']) &&  ! empty($params['template_name'])) {
            $data['template_name'] = $params['template_name'];
            $where .= " and template_name like '{$params['template_name']}%' ";
        }
        if (isset($params['default_template']) && !empty($params['default_template'])) {
            $where .= " and default_template = {$params['default_template']}";
        }
        if ( ! isset($params['page']) ||  ! is_numeric($params['page']) ) {
           $params['page'] = 1;
        }
        // 创建一个 DB 查询来获得所有 status 为 1 的文章
        $query = AutoMailTemplate::find()->where($where);
        // 得到文章的总数（但是还没有从数据库取数据）
        $count = $query->count();
        // 使用总数来创建一个分页对象
        $defualtPage = 20;
        $pagination = new Pagination([ 'defaultPageSize' => $defualtPage,'totalCount' => $count]);
        $pageStart = $params['page'] * $defualtPage;
        // 使用分页对象来填充 limit 子句并取得文章数据
        $res = $query->select('id,site_id,template_name,template_content')->orderBy('id desc')->offset(0)
            ->limit($defualtPage)->asArray()
            ->all();
        if (empty($res)) {
            self::success();
        }
        self::success($res);
    }


    /**
     *  模板信息
     *  id   auto_mail_template
     */
    public function actionTemplateInfo() {
        $params = $_REQUEST;
        if ( ! isset($params['id']) ||  ! is_numeric($params['id']) ) {
            self::error("id 不能为空");
        }
        // 添加模版类型
        $sql = "select id,site_id,template_name,template_content,ciphertext,type_id from auto_mail_template where id = {$params['id']} ";
        $res = yii::$app->db->createCommand($sql)->queryOne();
        if (empty($res)) {
            self::error("不存在相关信息");
        }
        // 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getMarketEmailAccessSite();
        $siteInfo[0] = "全部";
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
            }
        }
        $res['site_name'] = $siteInfo[$res['site_id']];
        self::success($res);
    }


    /**
     *  模板删除
     *  id
     *
     */
    public function actionDelTemplate() {
        $params = $_REQUEST;
      //  var_dump($params);die;
        $data = [];
        if (! isset($params['id']) || empty($params['id']) ) {
            self::error("模板id 不能为空");
        }
        $cond = ['id' => $params['id']];

        $sql = "select id from auto_mail_template where id = {$params['id']}";
        $mailTemplateInfo = yii::$app->db->createCommand($sql)->queryOne();
        if (empty($mailTemplateInfo)) {
            self::error("此信息不存在");
        }
        if (! empty($mailTemplateInfo['is_del'])) {
            self::success([],'已经删除，无需再次删除');
        }
        $data = ['is_del' => 1];
        Yii::$app->db->createCommand()->update('auto_mail_template',$data, $cond)->execute();
       // $res = Yii::$app->db->createCommand()->update('auto_mail_template',$data, $cond)->execute();
//        if(empty($res)) {
//            self::error();
//        }

        return self::actionIndex();
    }





    /**
     *
     *
     *  curl http://10.40.6.50:2087/gateway/ -d '{"header": {"service": "com.globalegrow.spi.mgoods.common.inter.IGoodsListAggregateService","method": "queryGoodsSimpleInfo","domain": "","version": "1.0.0","tokenId": "450aeab18f48b2c3f03a3eb9e3f38766"},"body": {"goodSnList": ["CA0001101","CA0001102"],"lang": "en","pageNo": 1,"pageSize": 20,"shopCode": "888888888888888888","siteCode": "GB","startNum": 0,"virWhCode": "1433363"}}' |jq .
     *  goodSnStr
     *  lang 语言编码
     *  virWhCode 销售仓库编码
     * // shopCode 店铺编码
     *  siteCode 站点简洁编码
     *  regSource  注册来源
     *
     */
    public function actionGetShopInfo()
    {   $msg = '系统繁忙~';
        $params = $_REQUEST;
        if (! isset($params['goodSnStr']) || empty($params['goodSnStr'])) {
            self::error('sku_str 编码不能为空');
        }
        if (! isset($params['virWhCode']) || empty($params['virWhCode'])) {
            self::error( 'virWhCode 不能为空');
        }
        if (! isset($params['siteCode']) || empty($params['siteCode'])) {
            self::error('siteCode 编码不能为空');
        }
        if (! isset($params['lang']) || empty($params['lang'])) {
            self::error('lang 类型不能为空');
        }
        if (! isset($params['regSource']) || empty($params['regSource'])) {
            self::error('regSource 类型不能为空');
        }
        //$params['goodSnStr'] = "CA0001101,CA0001102,CA0001104";
        $goodSnArr = explode(',',$params['goodSnStr']);
        $bodyInfo = [
            'lang' => $params['lang'],
            'siteCode' => $params['siteCode'],
            'virWhCode' => $params['virWhCode'],
            'startNum' => 0,
            'pageNo' => 1,
            'pageSize' => 20
        ];
        $bodyInfo['goodSnList'] = $goodSnArr;
        $site = "gearbest";
        // 组装相关数据
        $infoPostDeal = [];
        $infoPostDeal['header'] = json_decode($this->header[$site]['queryGoodsSimpleInfo'],true);
        $infoPostDeal['body'] = $bodyInfo;
        $res = self::getAOS($infoPostDeal,$msg);
        if (empty($res)) {
            self::error("暂无数据");
        }
        $url = "https://" . $params['regSource'] .".gearbest.com";
        self::msoaUrlFill($res,$url);
        self::success($res);
        //获取商品的价格和优化价格
    }

    /*
     *  goodSnstr
     *  virWhCode
     *  siteCode
     *  lang
     *  regSource
     *
     */
    public function getShopInfo($info,$prefix='')
    {
        $msg = '系统繁忙~';
        if (! isset($info['goodSnStr']) || empty($info['goodSnStr'])) {
            return false;
        }
        if (! isset($info['virWhCode']) || empty($info['virWhCode'])) {
            return false;
        }
        if (! isset($info['siteCode']) || empty($info['siteCode'])) {
            return false;
        }
        if (! isset($info['lang']) || empty($info['lang'])) {
            return false;
        }
        if (! isset($info['regSource']) || empty($info['regSource'])) {
            return false;
        }
        //$params['goodSnStr'] = "CA0001101,CA0001102,CA0001104";
        $goodSnArr = explode(',',$info['goodSnStr']);
        $bodyInfo = [
            'lang' => $info['lang'],
            'siteCode' => $info['siteCode'],
            'virWhCode' => $info['virWhCode'],
            'startNum' => 0,
            'pageNo' => 1,
            'pageSize' => 20
        ];
        $bodyInfo['goodSnList'] = $goodSnArr;
        $site = "gearbest";
        // 组装相关数据
        $infoPostDeal = [];
        $infoPostDeal['header'] = json_decode($this->header[$site]['queryGoodsSimpleInfo'],true);
        $infoPostDeal['body'] = $bodyInfo;

        $msgT = "in the getShopInfo Info" . \GuzzleHttp\json_encode($infoPostDeal);
        Elog::logMarketing($msgT,"autoTemplate","info");

        $res = self::getAOS($infoPostDeal,$msg);
        if (empty($res)) {
            $msg = $prefix . $msg;
            self::error("{$msg}");
        }
        $url = "https://" . $info['regSource'] .".gearbest.com";
        self::msoaUrlFill($res,$url);
        return $res;
    }




    /**
     *  获取商品详情
     *  curl http://10.40.6.50:2087/gateway/ -d '{"header": {"service": "com.globalegrow.spi.mgoods.common.inter.IGoodsListAggregateService","method": "queryGoodsSimpleInfo","domain": "","version": "1.0.0","tokenId": "450aeab18f48b2c3f03a3eb9e3f38766"},"body": {"goodSnList": ["CA0001101","CA0001102"],"lang": "en","pageNo": 1,"pageSize": 20,"shopCode": "888888888888888888","siteCode": "GB","startNum": 0,"virWhCode": "1433363"}}' |jq .
     *  goodSnStr
     *  lang 语言编码
     *  virWhCode 销售仓库编码
     * // shopCode 店铺编码
     *  siteCode 站点简洁编码
     *  regSource  注册来源
     *  currencyCode 币种
     *  pipelineCode 渠道来源
     */
    public function actionGetShopDetail() {
        $params = $_REQUEST;
        if (! isset($params['goodSnStr']) || ! is_array($params['goodSnStr'])) {
            self::error('sku_str 必须为数组类型');
        }
        if (! isset($params['virWhCode']) || ! is_array($params['virWhCode'])) {
            self::error( 'virWhCode 必须为数组类型');
        }
        if (! isset($params['siteCode']) || empty($params['siteCode'])) {
            self::error('siteCode 编码不能为空');
        }
        if (! isset($params['lang']) || empty($params['lang'])) {
            self::error('lang 类型不能为空');
        }
        if (! isset($params['regSource']) || empty($params['regSource'])) {
            self::error('regSource 类型不能为空');
        }
        if (! isset($params['pipelineCode']) || empty($params['pipelineCode'])) {
            self::error('渠道来源不能为空');
        }
        if (! isset($params['ciphertext'])) {
           $params['ciphertext'] = '';
        }
        $info = [];
        $shopInfo = [];
        foreach ($params['virWhCode'] as $key => $val) {
            $info['goodSnStr'] = $params['goodSnStr'][$key];
            $info['virWhCode'] = $val;
            $info['lang'] = $params['lang'];
            $info['siteCode'] = $params['siteCode'];
            $info['regSource'] = $params['regSource'];
            $index = $key +1;
            $temp = self::getShopInfo($info,"第{ $index }个仓库的");
            $shopInfo = array_merge($shopInfo,$temp);
        }
        if (empty($shopInfo)) {
            self::error('没有更多信息');
        }


        $commodityPriceCond = [];   //组合商品价格条件
        $shopPriceCond = [];       // 本店售价条件
        $index = 0 ;
        foreach ($shopInfo as $val) {
            $tmp = [
                'pipelineCode' => $params['pipelineCode'],
                'warehouseCode' => $val['virWhCode'],
                'goodSn' => $val['goodSn'],
                //'ciphertext' => $params['ciphertext'],    //密文
                ];
            $tmp2 =[
                'pipelineCode' => $params['pipelineCode'],
                'virWhCode' => $val['virWhCode'],
                'goodSn' => $val['goodSn']
            ];
            if (! empty($params['ciphertext'])) {
                $tmp['ciphertext'] = $params['ciphertext'];    //密文
            }
            $commodityPriceCond[$index] = $tmp;
            $shopPriceCond[$index] = $tmp2;
            ++$index;

        }

        $site = "gearbest";
//        //获取价格和优化价格
        $getCommodityPrice['header'] = json_decode($this->header[$site]['getPriceList'],true);
        $getCommodityPrice['body'] =  [
            "siteCode"=> $params['siteCode'],
            "goodPriceReqs"=> $commodityPriceCond,
        ];

        // 本店售价条件
        $getShopPrice['header'] = json_decode($this->header[$site]['batchQueryGoodsPriceInfoList'],true);
        $getShopPrice['body'] =  [
            "siteCode"=> $params['siteCode'],
            "reqList"=> $shopPriceCond,
        ];

        $msgt = "in the actionGetShopDetail mothed,get commodity price Info" . \GuzzleHttp\json_encode($getCommodityPrice);
        Elog::logMarketing($msgt,"autoTemplate","info");
        $commodityPriceList = self::getAOS($getCommodityPrice,$msg);
        // 有币种，价格统一转换
        if (empty($commodityPriceList) || ! isset($commodityPriceList['goodPrices'])) {
            self::error("{$msg}");
        }

        $commodityPriceList = $commodityPriceList['goodPrices'];
        $commodityPriceList = self::arrKeyToIndex($commodityPriceList,"goodSn");

        //获取本店售价
        $msgt = "in the actionGetShopDetail mothed,get shop price Info" . \GuzzleHttp\json_encode($getShopPrice);
        Elog::logMarketing($msgt,"autoTemplate","info");
        $shopPriceList = self::getAOS($getShopPrice,$msg);
        if (! empty($shopPriceList)) {
            $shopPriceList = self::arrKeyToIndex($shopPriceList,"goodSn");
        }
        foreach ($shopInfo as $key  => & $val ) {
            $val['price_detail'] = [];
            $val['price'] = 0;
            $val['shopPrice'] = -1;
            if (isset($commodityPriceList[$val['goodSn']]) && isset($commodityPriceList[$val['goodSn']]['price'])) {
                $val['price_detail'] = $commodityPriceList[$val['goodSn']];
                $val['price'] = $commodityPriceList[$val['goodSn']]['price'];
            }else {  //记录日志
                $msgT = "There is no corresponding price for goods.goods Info" . \GuzzleHttp\json_encode($val);
                Elog::logMarketing($msgT,"autoTemplate","info");
            }
            if (isset($shopPriceList[$val['goodSn']]) && isset($shopPriceList[$val['goodSn']]['shopPrice'])) {
                $val['shopPrice'] = $shopPriceList[$val['goodSn']]['shopPrice'];    //本店售价价格
            }
        }
        unset($val,$commodityPriceList,$getCommodityPrice,$commodityPriceCond,$getShopPrice,$shopPriceCond,$shopPriceList);
        // 判断是否有币种，有币种获取币种的转换率，
        if (isset($params['currencyCode']) && ! empty($params['currencyCode'])) {
            $price = self::exchangeRate($params['siteCode'],$params['currencyCode']);

            if (empty($price)) {
                self::error("币种转换失败");
            }
            $specialCurrency = [
                 "JPY","CLP","KRW","IDR","HUF","TWD","IOD"
            ];
            $accuracy =  (in_array($params['currencyCode'],$specialCurrency)) ? 0: 2;

            //价格
            foreach ($shopInfo as & $val ) {
               $val['price'] = round($val['price'] * $price,$accuracy);
               $val['shopPrice'] = round($val['shopPrice'] * $price,$accuracy);
               $val['exchangeRate'] = $price;
               $val['currencyCode'] = $params['currencyCode'];
            }
        }

        self::success($shopInfo,'成功');
    }




    public function getAOS($data,& $msg='系统繁忙') {
        if ( ! isset($data['header'],$data['body']) || empty($data['header']) || empty($data['body'])) {
            return [];
        }
        $mark = "\tin the actionSendPremiumPrice function:\t";
        $res = self::curlPost($this->getPriceApiUrl[YII_ENV],$data,true);
        if (empty($res)) {
            $mark .= "curl request information ".json_encode($data). "response infomation " .$res;
            Elog::logAdmin($mark, 'AutoTemplate','info'); // 记录信息到elog
            return [];
        }
        $info = json_decode($res,true);
        if (! isset($info['header']['code']) || ! empty($info['header']['code'])) {   //failed code != 0
            $mark .= "curl request information ".json_encode($data). "response infomation " .$res;
            Elog::logAdmin($mark, "AutoTemplate",'info'); // 记录信息到elog
            return [];
        }
        if (! isset($info['body']) && is_null(json_decode($info['body'],true))) {
            $mark .= "curl request information ".json_encode($data). "response infomation " .$res;
            Elog::logAdmin($mark, 'AutoTemplate','info'); // 记录信息到elog
            return [];
        }
        return json_decode($info['body'],true)['data'];
    }


    /**
     *  图片和网站url 拼接
     * {
    "shopCode":"888888888888888888",
    "virWhCode":"1433363",
    "mainImage":{
    "imgUrl":"gb/201306/goods-img/1371086641293-P-865934.jpg",
    "gridUrl":"gb/201306/grid-img/1371086641940-P-865934.jpg",
    "originalUrl":"gb/201306/source-img/1371086641100-P-865934.jpg",
    "thumbUrl":"gb/201306/thumb-img/1371086641998-thumb-P-865934.jpg"
    },
    "goodsWebSku":"009601002997",
    "urlTitle":"/cell-phones/pp_4435.html",
    "goodSn":"CA0001101",
    "goodTitle":"Baseus Cool Brushed Call ID View PU Leather and Plastic Cover Case for B9500 - Green"
    },
     */
    public function msoaUrlFill(& $data,$web_site_url) {
         if (empty($data)) {
             return [];
         }
         // {网站域名} .gearbest.com/{urltile}/pp_{外部SKU}?wid={销售仓编码}
         $image_prefix = "https://gloimg.gbtcdn.com/";
         foreach($data as & $val) {
             $val['urlTitle'] = $web_site_url .$val['urlTitle']."?wid=".$val['virWhCode'];
             if ( empty($val['mainImage']) || ! is_array($val['mainImage'])) {
                 continue;
             }
             foreach($val['mainImage'] as & $v) {
                 $v = $image_prefix .$v;
             }
         }
        return ;
    }



    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @return  string
     */
    public function curlPost($url,$params=[]){
       // $data_string =$params;
        $data_string = json_encode($params);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_PROXY, '');
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_string))
        );
        $result = curl_exec($ch);
        return $result;
    }


    /**
     *  自定义模板入口
     *
     */
    public function actionIndex()
    {
        $defualtPage = 20;
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
        // 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getMarketEmailAccessSite();
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
            }
        }
        if (empty($siteInfo)) {
            exit('你好，你没有任何网站的相关权限');
        }
        $customeTemplateSite = Yii::$app->params['sites']['marketing_email']['web_index'];
        $customeTemplateSite = array_intersect($siteInfo,$customeTemplateSite);
        $params = $_REQUEST;
        $data = [];
        //如果没有穿站点 ID，则返回第一个站点的
        if(!isset($params['site_id']) || empty($params['site_id'])){
            $params['site_id'] = key($customeTemplateSite);
        }

        $where = " is_del = 0 and default_template = 0 ";      //只展示没有删除的模板
        if ( isset($params['site_id'])&&  ! empty($params['site_id']) ) {
            $data['site_id'] = $params['site_id'];
            $where .= " and site_id = {$params['site_id']}  ";
        }
        if ( isset($params['template_name']) &&  ! empty($params['template_name'])) {
            $data['template_name'] = $params['template_name'];
            $where .= " and template_name like '%{$params['template_name']}%' ";
        }

        if ( ! isset($params['page']) ||  ! is_numeric($params['page']) ) {
            $params['page'] = 1;
        }

        if(isset($params['pagesize']) && !empty($params['pagesize'])){
            $defualtPage = $params['pagesize'];
        }

        // 创建一个 DB 查询来获得所有 status 为 1 的文章
        $query = AutoMailTemplate::find()->where($where);
        // 得到文章的总数（但是还没有从数据库取数据）
        $totalCount = $query->count();
        if ($params['page'] >= 1 ) {  //初始页从0开始
            $params['page'] = $params['page'] - 1;
        }
        // 使用总数来创建一个分页对象
        $pageStart = $params['page'] * $defualtPage;
        // 使用分页对象来填充 limit 子句并取得文章数据
        $res = $query->select('id,add_said,site_id,template_name,template_content,last_modify')->orderBy('id desc')->offset($pageStart)
            ->limit($defualtPage)->asArray()
            ->all();
        if (! isset($params['site_id']) || empty($params['site_id'])) {
            $site_id = 0;
        }else{
            $site_id = $params['site_id'];
        }
      
        // 分页相关
        $pages = new Pagination(['totalCount' =>$totalCount, 'pageSize' => $defualtPage, 'defaultPageSize' => $defualtPage]);
        // var_dump(self::siteIdList());die;
        $site_id_list = self::siteIdList();
        return $this->render('/marketing/auto-template/index',[
            'data' => $res,
            'site' => $site,
            'pages' => $pages,
            'site_id' => $site_id,
            'site_id_list' => $site_id_list,
            'cur_page' => $params['page'],
            'site_id_list'=>$customeTemplateSite,
            'site_id'=>isset($params['site_id'])?$params['site_id']:0,
        ]);
        //return $this->render('index');
    }

    
    
    
    /**
     * 预览
     *
     *
     */
    public function actionPreview() {
        $params = $_REQUEST;
        if ( ! isset($params['id']) ||  ! is_numeric($params['id']) ) {
            self::error("id 不能为空");
        }
        // 添加模版类型
        $sql = "select id,site_id,template_name,template_content from auto_mail_template where id = {$params['id']} ";
        $info = yii::$app->db->createCommand($sql)->queryOne();
        return $this->renderPartial('preview',$info);
    }

    /**
     *  获取仓库信息
     *  siteCode 网站简称 默认为GB
     */
    public function actionGetWebSiteList() {
        $msg = '系统繁忙~';
        $params = $_REQUEST;
        if (! isset($params['siteCode']) && empty($params['siteCode'])) {
            self::error("siteCode不能为空");
        }
        $bodyInfo = [
            'siteCode' => $params['siteCode']
        ];
//        $header = [
//            'service' => 'com.globalegrow.spi.mstock.inter.IVirtualWarehouseService',
//            'method' => 'getVirtualWareshouseList',
//            'domain' =>"",
//            'version' => '1.0.0',
//            'tokenId' => $this->tokenId[YII_ENV]
//        ];
        $site = "gearbest";
        $header =json_decode($this->header[$site]['getVirtualWareshouseList'],true);

        $infoPostDeal['body'] = $bodyInfo;
        $infoPostDeal['header'] = $header;
        $msg = "系统繁忙~";
        $res = self::getAOS($infoPostDeal,$msg);

        if (empty($res)) {
            self::error($msg);
        }
        $info  =[];
        foreach ($res as $val) {
            if (empty($val['status'])) {
                continue;
            }
            $info[] = $val;
        }
        self::success($info);
    }

    /**
     *  语言列表
     *
     */
    public function actionSourceList () {
      $languageList =
          [
            "en" => "英语",
            "fr"=> "法语",
            "ep" => "西班牙语",
            "ru" =>"俄语",
            "po" => "葡萄牙语",
            "it" => "意大利语",
            "de" => "德语",
            "en-gb" => "英国英语",
            "en-us" =>"美国英语",
            "pt-br" => "巴西葡萄牙语",
            "tr" =>	"土耳其语",
            "ch" =>	"中文繁体",
            "cn" =>"中文简体"
          ];
//      $regSourceList =
//          [
//          'www' => '全球站',
//	      'uk' => '英国站',
//          'es' => '西班牙站',
//          'pt' => '葡萄牙站',
//          'de' => '德国站',
//          'ru' => '俄罗斯站',
//          'it' => '意大利站',
//          'us' => '美国站',
//          'br' => '巴西站',
//          'fr' => '法国站',
//          'tr' => '土耳其站',
//          ];
        $regSourceList =
            [
                '全球站' =>['regSource' => 'www','pipelineCode' =>'GB'],
                '英国站' =>['regSource' => 'uk','pipelineCode' =>'GBUK'],
                '西班牙站' =>['regSource' => 'es','pipelineCode' =>'GBES'],
                '葡萄牙站' =>['regSource' => 'pt','pipelineCode' =>'GBPT'],
                '德国站' =>['regSource' => 'de','pipelineCode' =>'GBDE'],
                '俄罗斯站' =>['regSource' => 'ru','pipelineCode' =>'GBRU'],
                '意大利站' =>['regSource' => 'it','pipelineCode' =>'GBIT'],
                '美国站' =>['regSource' => 'us','pipelineCode' =>'GBUS'],
                '巴西站' =>['regSource' => 'br','pipelineCode' =>'GBBR'],
                '法国站' =>['regSource' => 'fr','pipelineCode' =>'GBFR'],
                '土耳其站' =>['regSource' => 'tr','pipelineCode' =>'GBTR']
            ];
      self::success(['regSourceList' => $regSourceList,'languageList' => $languageList]);
    }


    /**
     *  自定义模板入口
     *
     */
    public function actionContent()
    {
        Yii::$app->params['now_addr'] = "自定义模板";
        $params = $_REQUEST;
        $str = "/custom-template/index.html?";
        if ( isset($params['type']) &&  ! empty($params['type']) ) {
           $str .= "type={$params['type']}&";
        }
        if ( isset($params['id']) &&  ! empty($params['id']) ) {
            $str .= "id={$params['id']}&";
        }
        $str = rtrim($str,'&');
        return $this->render('content',['url' => $str]);
    }

    /*
     * 模板内容下载
     * @liugang 2018-06-23
     */
    public function actionDownload()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $id = Yii::$app->request->$mothod('id');
        $id = $id ? intval($id) : 0;
        if(!$id) {
            $this->sysMsg('警告', '参数不存在!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        
        $sql = "select id,site_id,template_name,template_content from auto_mail_template where id = $id ";
        $res = yii::$app->db->createCommand($sql)->queryOne();
        if(!$res) {
            $this->sysMsg('警告', '模板数据不存在!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        
        // 下载文件
        $downloadFilename = 'template.html';
            
        // 下载文件输出头
        header('Content-Description: File Transfer');
        header('Content-Type: text/html');
        header('Content-Disposition: attachment; filename="'. $downloadFilename .'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        
        echo $res['template_content'];
        //刷新输出缓冲到浏览器
        ob_flush();
        flush();//必须同时使用 ob_flush() 和flush() 函数来刷新输出缓冲。
    }

    /*
     *  获取币种信息
     *  $siteCode 站点
     *  $currencyCode 美元转换到指定国家的汇率
     *  date 2018-6-29
     *
     */

    public function exchangeRate($siteCode,$currencyCode) {
        $msg ='暂无数据';
        if (empty($siteCode) || empty($currencyCode)) {
            return false;
        }
        $bodyInfo = [
            'siteCode' => $siteCode,
            'currencyName' => $currencyCode
        ];
        $site = "gearbest";
        // 组装相关数据
        $infoPostDeal = [];
        $infoPostDeal['header'] = json_decode($this->header[$site]['querySiteCurrencyRateList'],true);
        $infoPostDeal['body'] = $bodyInfo;
        $res = self::getAOS($infoPostDeal,$msg);
        if (empty($res) || ! isset($res[0]['currencyRate'])) {
            self::error($msg);
        }
        return $res[0]['currencyRate'];
    }

    public function actionExchangeRateList() {
        $params = $_REQUEST;
        $siteCode = 'GB';
        $currencyCode = 'CNY';
        if ( isset($params['currencyCode'])) {
            $currencyCode = $params['currencyCode'];
        }

        $bodyInfo = [
            'siteCode' => $siteCode
        ];
        $site = "gearbest";
        // 组装相关数据
        $infoPostDeal = [];
        $infoPostDeal['header'] = json_decode($this->header[$site]['querySiteCurrencyRateList'],true);
        $infoPostDeal['body'] = $bodyInfo;
        $res = self::getAOS($infoPostDeal,$msg);
        if (empty($res)) {
            self::error("暂无数据");
        }
        if (isset($params['currencyCode'])) {
            $exchangeRate = self::arrKeyToIndex($res['currencyDtos'],'currencyCode');
            var_dump($exchangeRate[$currencyCode]['currencyRate']);
        }else {
            echo "<pre/>";
            print_r($res);
            die;
        }

        /*
         //提取json
        foreach ($res['currencyDtos'] as & $val) {
            unset($val['currencyPosition'],$val['isAutoSwitch'],$val['exponent'],$val['siteCode'],$val['currencyRate']);
        }
        echo \GuzzleHttp\json_encode($res['currencyDtos']);die;
       */

    }


    /**
     * 获取自定义模板的站点列表
     */
    public function actionSiteCodeList() {
        $siteInfo_tmp = Yii::$app->authority->getMarketEmailAccessSite();
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_k] = [
                    'site_id'=>$siteInfo_tmp_v['site_id'],
                    'site_code'=>$siteInfo_tmp_v['brief_code'],
                ];
            }
        }
        if (empty($siteInfo)) {
            self::error('你好，你没有任何网站的相关权限');
        }
        self::success($siteInfo);
    }


    /**
     *
     *   currencyName":"美元",
     *   currencySign":"$",
     *   currencyCode":"USD"
     *
     */

    public function actionCurrencyList() {
        $str = '[{"currencyName":"\u7f8e\u5143","currencySign":"$","currencyCode":"USD"},{"currencyName":"\u6b27\u5143","currencySign":"\u20ac","currencyCode":"EUR"},{"currencyName":"\u82f1\u78c5","currencySign":"\u00a3","currencyCode":"GBP"},{"currencyName":"\u6fb3\u5143","currencySign":"AU$","currencyCode":"AUD"},{"currencyName":"\u52a0\u5143","currencySign":"C$","currencyCode":"CAD"},{"currencyName":"\u745e\u58eb\u6cd5\u90ce","currencySign":"SFr.","currencyCode":"CHF"},{"currencyName":"\u6e2f\u5e01","currencySign":"HK$","currencyCode":"HKD"},{"currencyName":"\u65b0\u897f\u5170\u5143","currencySign":"NZ$","currencyCode":"NZD"},{"currencyName":"\u65e5\u5143","currencySign":"\u00a0\u5186","currencyCode":"JPY"},{"currencyName":"\u4fc4\u56fd\u5362\u5e03","currencySign":"\u0440\u0443\u0431.","currencyCode":"RUB"},{"currencyName":"\u5df4\u897f\u96f7\u4e9a\u5c14","currencySign":"R$","currencyCode":"BRL"},{"currencyName":"\u632a\u5a01\u514b\u7f57\u94a0","currencySign":"NKr.\u00a0","currencyCode":"NOK"},{"currencyName":"\u4e39\u9ea6\u514b\u7f57\u94a0","currencySign":"DKr.","currencyCode":"DKK"},{"currencyName":"\u745e\u5178\u514b\u6717","currencySign":"SKr","currencyCode":"SEK"},{"currencyName":"\u4ee5\u8272\u5217\u65b0\u9521\u514b\u5c14","currencySign":"\u20aa","currencyCode":"ILS"},{"currencyName":"\u54e5\u4f26\u6bd4\u4e9a\u6bd4\u7d22","currencySign":"Col$","currencyCode":"COP"},{"currencyName":"\u58a8\u897f\u54e5\u6bd4\u7d22","currencySign":"MXN$","currencyCode":"MXN"},{"currencyName":"\u6cf0\u94e2","currencySign":"\u0e3f","currencyCode":"THB"},{"currencyName":"\u5370\u5c3c\u5362\u6bd4","currencySign":"Rp","currencyCode":"IDR"},{"currencyName":"\u6ce2\u5170\u5179\u7f57\u63d0","currencySign":"z\u0142","currencyCode":"PLN"},{"currencyName":"\u5308\u7259\u5229\u798f\u6797","currencySign":"Ft","currencyCode":"HUF"},{"currencyName":"\u571f\u8033\u5176\u91cc\u62c9","currencySign":"TL","currencyCode":"TRY"},{"currencyName":"\u9a6c\u6765\u897f\u4e9a\u6797\u5409\u7279","currencySign":"RM","currencyCode":"MYR"},{"currencyName":"\u5c3c\u65e5\u5229\u4e9a\u5948\u62c9","currencySign":"\u20a6","currencyCode":"NGN"},{"currencyName":"\u5357\u975e\u5170\u7279","currencySign":"R","currencyCode":"ZAR"},{"currencyName":"\u683c\u91cc\u592b\u7eb3","currencySign":"\u20b4","currencyCode":"UAH"},{"currencyName":"\u65b0\u5143","currencySign":"S$","currencyCode":"SGD"},{"currencyName":"\u65b0\u53f0\u5e01","currencySign":"NT$","currencyCode":"TWD"},{"currencyName":"\u6c99\u7279\u91cc\u4e9a\u5c14","currencySign":"\u0631.\u0633","currencyCode":"SAR"},{"currencyName":"\u585e\u5c14\u7ef4\u4e9a\u7b2c\u7eb3\u5c14","currencySign":"\u0420\u0421\u0414","currencyCode":"RSD"},{"currencyName":"\u7f57\u9a6c\u5c3c\u4e9a\u5217\u4f0a","currencySign":"lei","currencyCode":"RON"},{"currencyName":"\u79d8\u9c81\u7d22\u5c14","currencySign":"S\/.","currencyCode":"PEN"},{"currencyName":"\u4fdd\u52a0\u5229\u4e9a\u5217\u5f17","currencySign":"\u043b\u0432","currencyCode":"BGN"},{"currencyName":"\u667a\u5229\u6bd4\u7d22","currencySign":"CL$","currencyCode":"CLP"},{"currencyName":"\u4eba\u6c11\u5e01","currencySign":"\u00a5","currencyCode":"CNY"},{"currencyName":"\u6377\u514b\u514b\u6717","currencySign":"K\u010d","currencyCode":"CZK"},{"currencyName":"\u514b\u7f57\u5730\u4e9a\u5e93\u7eb3","currencySign":"Kn","currencyCode":"HRK"},{"currencyName":"\u5370\u5ea6\u5362\u6bd4","currencySign":"Rs","currencyCode":"INR"},{"currencyName":"\u963f\u806f\u914b\u8fea\u62c9\u59c6","currencySign":"\u062f.\u0625","currencyCode":"AED"},{"currencyName":"\u6469\u6d1b\u54e5\u8fea\u62c9\u59c6","currencySign":"\u062f.\u0645.","currencyCode":"MAD"},{"currencyName":"\u97e9\u56fd\u5706","currencySign":"\u20a9","currencyCode":"KRW"},{"currencyName":"\u963f\u6839\u5ef7\u6bd4\u7d22","currencySign":"ARS$","currencyCode":"ARS"}]';
       $res = \GuzzleHttp\json_decode($str,true);
       self::success($res);
    }

    /***
     * 从多维数组或对象数组中构建一个映射
     * 根据$array 指定$array[$key]为key 名
     * For example,
     * $array = [
     *     ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
     *     ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
     *     ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
     * ];
     *
     * $result = self::arrKeyToIndex($array, 'name');
     * // the result is:
     * // [
     * //     'aaa' => ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
     * //     'bbb' => ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
     * //     'ccc' => ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
     * // ]
     *
     */
    private function arrKeyToIndex($array,$key) {
        if (empty($array) || empty($key)) {
            return false;
        }
        $res = [];
        foreach ( $array as $item) {
            if ( isset($item[$key])) {
                $res[$item[$key]] = $item;
            }
        }
        return $res;
    }

    /*
     * 站点列表
     */
    public function siteIdList() {
        return [0=>'全部',12 => 'gearbest',19 =>'zaful'];  
    }

    /*
     * 站点列表
     */
    public function actionSiteidList()
    {
        $res = self::siteIdList();
        self::success($res);
    }
}